from mtp.lib.plugin import Plugin
from mtp.lib.base import *
from mtp.config.environment import configure_mtp


class ConfigeratorController(BaseController):
    @needs_perm('configerator', 'manage')
    def index(self, format='html'):
        return render('/configerator/index.%s' % format)

    @needs_perm('configerator', 'manage')
    def configure_plugin(self, name):
        return render('/configerator/config_plugin.html')

    @needs_perm('configerator', 'manage')
    def enable_plugin(self, name):
        config['mtp.config']['plugin:%s' % name]['enabled'] = True
        config['mtp.config'].write()
        configure_mtp()

    @needs_perm('configerator', 'manage')
    def disable_plugin(self, name):
        config['mtp.config']['plugin:%s' % name]['enabled'] = False
        config['mtp.config'].write()
        configure_mtp()

    @needs_perm('configerator', 'manage')
    def reset_plugin(self, name):
        try:
            plugin = config['mtp.plugins'][name]
        except KeyError:
            abort(404)
        
        plugin.takedown()
        plugin.setup()


class ConfigeratorPlugin(Plugin):
    def __init__(self, **options):
        config['mtp.permissions']['configerator'].add('manage')

        config['mtp.controllers']['config'] = ConfigeratorController

        map = config['routes.map']
        map.connect('config', controller='config', action='index')
        map.connect('config.:format', controller='config', action='index')
        map.connect('config/', controller='config', action='index')
        map.connect('configure_plugin', 'config/plugin/:name', 
            controller='config', action='configure_plugin')
        map.connect('disable_plugin', 'config/plugin/:name/disable', 
            controller='config', action='disable_plugin')
        map.connect('enable_plugin', 'config/plugin/:name/enable', 
            controller='config', action='enable_plugin')
        map.connect('reset_plugin', 'config/plugin/:name/reset',
            controller='config', action='reset_plugin')


